package recfun
import common._

object Main {
  def main(args: Array[String]) {
    println("Pascal's Triangle")
    for (row <- 0 to 10) {
      for (col <- 0 to row)
        print(pascal(col, row) + " ")
      println()
    }
  }

  /**
   * Exercise 1
   */
  def pascal(c: Int, r: Int): Int = {
    if (c < 0 || r < 0 || c > r)
      throw new IllegalArgumentException;
    if (c == 0 || r == c) {
      1;
    } else {
      pascal(c - 1, r - 1) + pascal(c, r - 1);
    }

  }

  /**
   * Exercise 2
   */
  def balance(chars: List[Char]): Boolean = {
    balance(chars, 0);
  }

  def balance(chars: List[Char], left: Int): Boolean = {
    if (left < 0)
      false;
    else {
      if (chars.isEmpty) {
        left == 0;
      } else if (chars.head == '(') {
        balance(chars.tail, left + 1);
      } else if (chars.head == ')') {
        balance(chars.tail, left - 1);
      } else {
        balance(chars.tail, left);
      }
    }
  }

  /**
   * Exercise 3
   */
  def countChange(money: Int, coins: List[Int]): Int = {
    if (money < 0)
      0
    else if (money == 0 || coins.isEmpty) {
      0
    } else if (coins.tail.isEmpty) {
      if (money % coins.head == 0) 1 else 0
    } else {
      var x = money
      var s = 0
      while (x > 0) {
        s = s + countChange(x, coins.tail)
        x = x - coins.head
      }

      if (money % coins.head == 0) s = s + 1;

      s;
    }
  }
}
